package com.demo.cms.action.manage;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import com.demo.core.model.File;
import com.demo.core.model.Site;
import com.demo.core.service.ResourceService;
import com.demo.core.service.exception.FileCreateException;
import com.demo.security.annotation.function.Function;
import com.demo.webapp.action.PageAction;

/**
 * 
 * @author ryuu.kk
 *
 */
@Function(id = 101200, pid = 10, code = "manage.resource")
public class ResourceAction extends PageAction {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = 4425218969447047512L;

	/**
	 * 资源服务
	 */
	private ResourceService resourceService;
	
	/**
	 * 资源JSON字符串
	 */
	private String json;
	
	/**
	 * 资源地址
	 */
	private String path;
	
	/**
	 * 资源地址(批量)
	 */
	private List<String> paths;
	
	/**
	 * 资源内容
	 */
	private String content;
	
	/**
	 * 资源文件
	 */
	private File file;
	
	/**
	 * 资源文件列表
	 */
	private List<File> fileList;
	
	/**
	 * 文件上传
	 */
	private java.io.File[] upload;
	
	/**
	 * 上传文件的文件名
	 */
	private List<String> uploadFileName;
	
	/**
	 * 上传文件的文件类型
	 */
	private List<String> uploadContentType;
	
	/**
	 * 资源列表树
	 * @return String
	 */
	public String tree() {
		
		Site site = getSite();
		// 取得资源路径
		String resPath = site.getResPath();
		
		if (resPath == null || resPath.length() == 0) {
			resPath = com.demo.webapp.config.Constants.DEFAULT_RESOURCE_PATH;
		}
		
		resPath = getSession().getServletContext().getRealPath(resPath);
		resourceService.create(resPath);
		// Folder folder = resourceService.resourceFolder(url, FilterMode.all);
		json = resourceService.buildJson(resPath, null);
		
		return SUCCESS;
	}

	/**
	 * 资源一览
	 * 展示一个文件夹下的所有资源文件(不包含文件夹)
	 * @return String
	 */
	@Function(id = 101210, pid = 101200, code = "manage.resource.list")
	public String list() {
		
		if (validation()) {
			fileList = resourceService.resourceFileList(getSession().getServletContext().getRealPath("/"), path);
		} else {
			addActionError("用户越权访问资源文件.");
		}
		if (!piece) {
			tree();
		}
		return SUCCESS;
	}
	
	/**
	 * 创建目录
	 * @return String
	 */
	@Function(id = 101220, pid = 101200, code = "manage.resource.mkdir")
	public String mkdir() {
		
		if (validation()) {
			if (resourceService.create(getSession().getServletContext().getRealPath(path))) {
				addActionMessage("目录删除成功.");
			} else {
				addActionError("目录删除失败.");
			}
		}
		return CALLBACK;
	}
	
	/**
	 * 资源展示
	 * 展示一个资源文件
	 * @return String
	 * @throws IOException 
	 */
	public String view() throws IOException {
		
		if (validation()) {
	        if (file == null) {
	        	file = new File();
	        }
	        file.setPath(path);
	        file.setName(path.substring(path.lastIndexOf("/")));
	        byte[] buffer = null;
			try {
				buffer = resourceService.getContent(getSession().getServletContext().getRealPath(path));
			} catch (FileNotFoundException e) {
				log.warn(e.getMessage());
				addActionError(e.getMessage());
			}
	        file.setContent(buffer);
	        file.setContentType(path.substring(path.lastIndexOf(".") + 1).toLowerCase());
		} else {
			addActionError("用户越权访问资源文件.");
		}
		return SUCCESS;
	}
	
	/**
	 * 更新资源文件
	 * @return String
	 * @throws IOException I/O异常
	 * @throws FileCreateException 文件创建异常
	 */
	@Function(id = 101250, pid = 101200, code = "manage.resource.update")
	public String update() {
		
		if (validation()) {
			String name = path.substring(path.lastIndexOf("/") + 1);
			path = path.substring(0, path.lastIndexOf("/"));
			try {
				if (resourceService.create(getSession().getServletContext().getRealPath(path), name, content)) {
					addActionMessage("文件更新成功.");
				} else {
					addActionError("文件更新失败.");
				}
			} catch (FileCreateException e) {
				log.error(e.getMessage(), e);
				addActionError(e.getMessage());
			}
		} else {
			addActionError("用户越权访问资源文件.");
		}
		return CALLBACK;
	}
	
	/**
	 * 上传资源文件
	 * @return String
	 */
	@Function(id = 101270, pid = 101200, code = "manage.resource.upload")
	public String upload() {
		
		if (validation() && upload != null) {
			for (int i = 0; i < upload.length; i ++ ){
				if (resourceService.create(getSession().getServletContext().getRealPath(path), uploadFileName.get(i), upload[i])) {
					addActionMessage("文件上传成功.");
				} else {
					addActionError("文件上传失败.");
				}
			}
		}
		return CALLBACK;
	}
	
	/**
	 * 删除资源文件
	 * @return String
	 */
	@Function(id = 101260, pid = 101200, code = "manage.resource.delete")
	public String delete() {
		if (validation()) {
			try {
				if (resourceService.delete(getSession().getServletContext().getRealPath(path))) {
					addActionMessage("文件删除成功.");
				} else {
					addActionError("文件删除失败.");
				}
			} catch (FileNotFoundException e) {
				log.error(e.getMessage(), e);
				addActionError(e.getMessage());
			};
		} else {
			addActionError("用户越权访问资源文件.");
		}
		return CALLBACK;
	}
	
	/**
	 * 批量删除文件
	 * @return String
	 */
	@Function(id = 101280, pid = 101200, code = "manage.resource.rmdir")
	public String rmdir() {
		
		if (paths != null) {
			for (String path : paths) {
				// 批量地址验证
				if (validation()) {
					try {
						if (resourceService.delete(getSession().getServletContext().getRealPath(path))) {
							addActionMessage("文件删除成功.");
						} else {
							addActionError("文件删除失败.");
						}
					} catch (FileNotFoundException e) {
						log.error(e.getMessage(), e);
						addActionError(e.getMessage());
					}
				}
			}
		}
		return CALLBACK;
	}
	
	/**
	 * 删除目录
	 * @return String
	 */
	@Function(id = 101281, pid = 101200, code = "manage.resource.rd")
	public String rd() {
		
		if (validation()) {
			try {
				if (resourceService.delete(getSession().getServletContext().getRealPath(path))) {
					addActionMessage("目录删除成功.");
				} else {
					addActionError("目录删除失败.");
				}
			} catch (FileNotFoundException e) {
				log.error(e.getMessage(), e);
				addActionError(e.getMessage());
			}
		}
		return CALLBACK;
	}
	
	/**
	 * 对地址的验证
	 * @param path 路径
	 * @return boolean 验证状态
	 */
	private boolean validation() {
		
		Site site = getSite();
		
		// 取得资源路径
		String resPath = site.getResPath();
		if (resPath == null || resPath.length() == 0) {
			resPath = com.demo.webapp.config.Constants.DEFAULT_RESOURCE_PATH;
		}
		if (path == null) {
			path = resPath;
		}
		if (resPath.charAt(0) == '/') {
			resPath = resPath.substring(1);
		}
		if (path.charAt(0) == '/') {
			path = path.substring(1);
		}
		return path.startsWith(resPath);
	}
	
	public String getJson() {
		return json;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public List<String> getPaths() {
		return paths;
	}

	public void setPaths(List<String> paths) {
		this.paths = paths;
	}

	public List<File> getFileList() {
		return fileList;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void setUpload(java.io.File[] upload) {
		this.upload = upload;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public java.io.File[] getUpload() {
		return upload;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	} 
}
